<template>
  <div style="width: 100%">
    <div ref="main" :style="{height:height,width:width}" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  name: 'BarChart',
  mixins: [resize],
  props: {
    data: {
      type: Array,
      default: () => []
    },
    categories: {
      type: Array,
      default: () => []
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    autoResize: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      myChart: null // 这里增加了对 myChart 的引用
    }
  },
  watch: {
    data: {
      deep: true,
      handler(val) {
        this.initChart()
      },
      instance: null
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.resize())
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resize())
  },
  methods: {
    resize() {
      this.instance && this.instance.resize()
    },
    initChart() {
      var chartDom = this.$refs.main
      var myChart = echarts.init(chartDom, 'macarons')
      var option
      this.instance = myChart
      myChart.clear() // 将图表中的所有数据清楚
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.categories,
            axisLabel: {
              interval: 0, // 这会强制显示所有标签
              rotate: 45
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: this.data
          .filter(item => !item.data.every(value => value === 0))
          .map(item => ({
            name: item.name,
            type: 'bar',
            barWidth: 20,
            stack: item.stack,
            emphasis: {
              focus: 'series'
            },
            data: item.data
          }))
      }
      if (option)myChart.setOption(option) // 如果 option 不为空，就把 option 设置到 myChart
    }
  }
}
</script>

